package com.cuhk.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.cuhk.common.constant.ProductConstant;
import com.cuhk.common.to.SkuReductionTo;
import com.cuhk.common.to.SkuStockTo;
import com.cuhk.common.to.SpuBoundsTo;
import com.cuhk.common.to.es.SkuEsModel;
import com.cuhk.common.utils.R;
import com.cuhk.gulimall.product.entity.*;
import com.cuhk.gulimall.product.feign.CouponFeignService;
import com.cuhk.gulimall.product.feign.SearchFeignService;
import com.cuhk.gulimall.product.feign.WareFeignService;
import com.cuhk.gulimall.product.service.*;
import com.cuhk.gulimall.product.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Indexed;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cuhk.common.utils.PageUtils;
import com.cuhk.common.utils.Query;

import com.cuhk.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService attrValueService;

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private ProductAttrValueServiceImpl productAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SearchFeignService searchFeignService;

    @Autowired
    private SpuInfoDao spuInfoDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        // 1. 保存Spu基本信息 -> 存储到pms_spu_info表中
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        // saveBaseSpuInfo(spuInfoEntity);
        this.save(spuInfoEntity);

        // 2. 保存Spu描述图片 -> 存储到pms_spu_info_desc表中
        List<String> descript = spuSaveVo.getDescript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", descript));
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);

        // 3. 保存Spu图片集 -> 存储到pms_spu_images表中
        List<String> images = spuSaveVo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(), images);

        // 4. 保存Spu规格参数 -> 存储到pms_product_attr_value这张表中
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> list = baseAttrs.stream().map((attr) -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(attr.getAttrId());
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            productAttrValueEntity.setAttrValue(attr.getAttrValues());
            productAttrValueEntity.setQuickShow(attr.getShowDesc());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttr(list);

        // 5. 保存Spu积分信息 -> 设计跨库 gulimall-sms -> sms_spu_bounds
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        BeanUtils.copyProperties(bounds, spuBoundsTo);
        spuBoundsTo.setSpuId(spuInfoEntity.getId());
        // 调用远程服务保存
        couponFeignService.saveSpuBounds(spuBoundsTo);

        // 6. 保存当前Spu对应的所有Sku信息 -> 存储到
        // 6.1 pms_sku_info
        List<Skus> skuList = spuSaveVo.getSkus();
        if(skuList != null && skuList.size() > 0) {
            skuList.forEach(item -> {
                // 获取默认图片
                String defaultImg = "";
                for(Images img : item.getImages()) {
                    if(img.getDefaultImg() == 1) {
                        defaultImg = img.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSkuDefaultImg(defaultImg);

                // 保存sku基本信息
                skuInfoService.saveSkuInfo(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();

                List<SkuImagesEntity> skuImagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity -> {
                    // 返回true就可以通过过滤
                    return StringUtils.isNotBlank(entity.getImgUrl());
                }).collect(Collectors.toList());

                // 6.2 pms_sku_images
                // TODO 没有选中的图片，不需要保存，否则数据库中会出现无效记录

                skuImagesService.saveBatch(skuImagesEntities);

                // 6.3 pms_sku_sale_attr_value -> sku销售属性信息
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity saleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, saleAttrValueEntity);
                    saleAttrValueEntity.setSkuId(skuId);
                    return saleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                // 6.4 sku优惠、满减等信息
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                // 先判断一下满减信息有没有存储价值
                // 避免出现像"买0件，打0折"这样的问题
                if(skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(BigDecimal.ZERO) > 0) {
                    // 调用gulimall-coupon中的远程服务
                    couponFeignService.saveSkuReduction(skuReductionTo);
                }
            });
        }
    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();

        // 用户是否输入了关键字作为检索条件
        String key = (String) params.get("key");
        if(StringUtils.isNotBlank(key)) {
            wrapper.and((w) -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }
        // 用户是否输入了品牌作为检索条件
        String brandId = (String) params.get("brandId");
        if(StringUtils.isNotBlank(brandId)) {
            if(!"0".equalsIgnoreCase(brandId)) {
                wrapper.eq("brand_id", brandId);
            }
        }
        // 用户是否选择了类别作为检索条件
        String catelogId = (String) params.get("catelogId");
        if(StringUtils.isNotBlank(catelogId)) {
            if(!"0".equalsIgnoreCase(catelogId)) {
                wrapper.eq("catalog_id", catelogId);
            }
        }
        // 用户是否选择了状态作为检索条件
        String status = (String) params.get("status");
        if(StringUtils.isNotBlank(status)) {
            wrapper.eq("publish_status", status);
        }
        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

    @Override
    public void upShelf(Long spuId) {
        // 组装符合ES存储结构的数据
        List<SkuEsModel> upProducts = new ArrayList<>();
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);
        if(skus != null && !skus.isEmpty()) {

            // TODO (4) 查询attrs
            List<ProductAttrValueEntity> baseAttrs = productAttrValueService.baseAttrListForSpu(spuId);
            // 根据这个id序列
            // 利用AttrService查询pms_attr表，匹配那些search_type=1的数据项
            List<Long> targetAttrIds = baseAttrs.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());

            List<Long> targetSearchIds = attrService.selectSearchAttrs(targetAttrIds);
            HashSet<Long> searchSet = new HashSet<>(targetSearchIds);

            List<SkuEsModel.Attrs> attrsList = new ArrayList<>();
            for(ProductAttrValueEntity attrValueEntity : baseAttrs) {
                if(searchSet.contains(attrValueEntity.getAttrId())) {
                    SkuEsModel.Attrs attr = new SkuEsModel.Attrs();
                    attr.setAttrId(attrValueEntity.getAttrId());
                    attr.setAttrName(attrValueEntity.getAttrName());
                    attr.setAttrValue(attrValueEntity.getAttrValue());
                    attrsList.add(attr);
                }
            }

            // 封装每个sku的信息
            upProducts = skus.stream().map(sku -> {
                SkuEsModel skuEsModel = new SkuEsModel();
                BeanUtils.copyProperties(sku, skuEsModel);
                skuEsModel.setSkuPrice(sku.getPrice());
                skuEsModel.setSkuImg(sku.getSkuDefaultImg());

                // TODO (1) 调用gulimall-ware服务查询对应sku的库存信息 -> hasStock
                R res = wareFeignService.getSkuHasStock(sku.getSkuId());
                if(res.get("data") != null) {
                    SkuStockTo to = res.getData(new TypeReference<SkuStockTo>() {});
                    skuEsModel.setHasStock(to.getValidStock());
                }
                else {
                    skuEsModel.setHasStock(false);
                }

                // TODO (2) hotScore默认0
                skuEsModel.setHotScore(0L);

                // TODO (3) 查询、注入catelogName、catelogId、brandName和brandImg
                BrandEntity brandEntity = brandService.getById(sku.getBrandId());
                CategoryEntity categoryEntity = categoryService.getById(sku.getCatalogId());
                skuEsModel.setBrandName(brandEntity.getName());
                skuEsModel.setCatelogName(categoryEntity.getName());
                skuEsModel.setCatelogId(categoryEntity.getCatId());
                skuEsModel.setBrandImg(brandEntity.getLogo());

                // TODO (4) 注入attrs
                skuEsModel.setAttrs(attrsList);

                return skuEsModel;

            }).collect(Collectors.toList());
        }

        if(!upProducts.isEmpty()) {
            // 调用远程服务向ES提交数据
            R r = searchFeignService.productStatusUp(upProducts);
            if(r.get("code").equals(0)) {
                // TODO 商品上架成功
                // TODO 修改商品的上架状态
                spuInfoDao.updatePublishStatus(spuId, ProductConstant.StatusEnum.UP_SPU.getCode());
            } else {
                // TODO
                // Feign调用流程
                /**
                 * 1. 构造请求数据，将数据转化为JSON --> RequestTemplate template = buildTemplateFromArgs.create(argv);
                 * 2. 发送请求进行执行(执行成功会解码响应数据) --> executeAndDecode(template)
                 * 3. 执行请求会有重试机制，可以开启
                 */
            }
        }
    }

}